﻿using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ZilLion.Service.Core.Infrastructure.Filters;
using ZilLion.Service.Core.Log;
using ZilLion.Service.Core.Starter.Config;

namespace ZilLion.Service.Core.Starter
{
    public static class ZilLionServiceCoreExtensions
    {
        public static string DefaultCorsPolicyName = "localhost";

        public static IServiceCollection AddZilLionServiceCore(this IServiceCollection services)
        {
            #region MVC

            services.AddMvc(option =>
            {
                option.Filters.Add(new JwtTokenFilter());
                option.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
            }).AddControllersAsServices().AddJsonOptions(options =>
            {
                //使用驼峰样式的key
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.Error = (sender, args) =>
                {
                    var guid = Guid.NewGuid().ToString("N");

                    var msg =
                        $"在处理类型{args.ErrorContext.OriginalObject.GetType().Name}时发生错误,path为:{args.ErrorContext.Path},Member为:{args.ErrorContext.Member.ToString()}";
                    ZilLionLogManager.Instance().Warn(msg, tags: guid);
                    ZilLionLogManager.Instance().Error(args.ErrorContext.Error, tags: guid);
                };
            });

            #endregion

            #region 跨域

            services.AddCors(options => options.AddPolicy(DefaultCorsPolicyName,
                builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()
            ));

            #endregion

            SwaggerGenConfig.ConfigureServices(services);
            services.TryAddScoped<JwtInfoContainer>();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            return services;
        }      
    }
}